package com.example.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;


public class MyBatisUtil {
    private static final String RESOURCE = "mybatis-config.xml";

    private static class Holder {
        static final SqlSessionFactory INSTANCE = createInstance();
        private static SqlSessionFactory createInstance() {
            try (InputStream is = Resources.getResourceAsStream(RESOURCE)) {
                return new SqlSessionFactoryBuilder().build(is);
            } catch (IOException e) {
                throw new RuntimeException("Failed to initialize SqlSessionFactory", e);
            }
        }
    }

    public static SqlSessionFactory getSqlSessionFactory() {
        return Holder.INSTANCE;
    }
    public static SqlSession getSqlSession() {
        return getSqlSession(true);
    }
    public static SqlSession getSqlSession(boolean autoCommit) {
        SqlSessionFactory factory = getSqlSessionFactory();
        if(factory == null){
            throw new RuntimeException("SqlSessionFactory not initialized");
        }
        return factory.openSession(autoCommit);
    }
}
